
var expireTime=1000 * 60 * 60 *24; //24小时

// 保存token到本地存储
function setToken(token) {
    var time = new Date().getTime();
    localStorage.setItem('localTokenStartTime',time)
    localStorage.setItem('localToken', token);
}

// 从本地存储获取token
function getToken() {
    var lastTime = localStorage.getItem('localTokenStartTime');
    if (!lastTime || new Date().getTime() - lastTime >= expireTime){
        localStorage.removeItem('localToken');
        window.location.href="/pages/login.html"
        return null;
    }
    return localStorage.getItem('localToken');
}


function getAxiosConfig(){
    const axiosConfig = {
        headers: {
            Authorization: getToken(), // 添加 Authorization 头部
        },
    };
    return axiosConfig;
}

function loadToken(){
    const username = prompt('Please enter username:');
    const password = prompt('Please enter passowrd:');
    if (username !== null && password!=null) {
        login(username,password)
    } else {
        alert('User canceled input.');
    }
}

function login(username,password){
    axios.get("/auth?username="+username+"&password="+password).then((res)=>{
        if (res.data.success){
            var token=res.data.data;
            setToken(token);
            window.location.href="/pages/admin.html"
        }else {
            alert("登录失败!")
        }
    }).catch((error)=>{
        if (error == "Error: Request failed with status code 403"){
            this.$message.error("无操作权限");
        }
    });
}

function clearLocalToken(){
    localStorage.removeItem('localToken');
    localStorage.removeItem('localTokenStartTime');
    alert("退出登录成功!")
}